package com.cloud.messenger.client;

import com.cloud.messenger.api.MessageInfo;
import com.cloud.messenger.configuration.MessengerConfiguration;
import com.cloud.messenger.info.MailInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Data
@Slf4j
public class MailMessageClient implements MessengerClient {

    private String client;

    private MessengerConfiguration.MailProperties mailProperties;

    public JavaMailSender init(){
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(mailProperties.getHost());
        sender.setPort(mailProperties.getPort());
        sender.setPassword(mailProperties.getPassword());
        sender.setProtocol(mailProperties.getProtocol());
        sender.setDefaultEncoding(mailProperties.getDefaultEncoding());
        sender.setJavaMailProperties(mailProperties.getProperties());
        return sender;
    }

    @Override
    public void send(MessageInfo messageInfo) {
        JavaMailSender javaMailSender = init();
        MailInfo mailInfo=new MailInfo();
        MimeMessage mimeMailMessage = null;
        try {
            mimeMailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(mailInfo.getFrom());
            mimeMessageHelper.setTo(mailInfo.getTo());
            mimeMessageHelper.setCc(mailInfo.getCc());
            mimeMessageHelper.setBcc(mailInfo.getBcc());
            mimeMessageHelper.setSubject(mailInfo.getSubject());
            mimeMessageHelper.setText(mailInfo.getText());
//            mimeMessageHelper.addInline();
//            mimeMessageHelper.addAttachment();
            javaMailSender.send(mimeMailMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
